import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiResponse } from '@/common/interfaces/response.interface';
import { getCurrentContext } from '@/common/async-context';

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, ApiResponse<T>> {
    intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponse<T>> {
        const currentContext = getCurrentContext();

        return next.handle().pipe(
            map((data) => {
                // 如果响应已经是标准格式，直接返回
                if (data && typeof data === 'object' && 'code' in data && 'msg' in data && 'data' in data) {
                    return {
                        ...data,
                        timestamp: data.timestamp || new Date().toISOString(),
                        traceId: currentContext?.traceId || 'unknown',
                    };
                }

                // 包装为标准响应格式
                return {
                    code: 200,
                    msg: 'success',
                    data: data,
                    timestamp: new Date().toISOString(),
                    traceId: currentContext?.traceId || 'unknown',
                };
            }),
        );
    }
}
